/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package CONTROLLERS;

import BEANS.ComboItem;
import BEANS.Product;
import UTIL.TableManager;
import UTIL.DatabaseConnector;
import UTIL.InputValidator;
import VIEW.ProductsUI;
import datechooser.beans.DateChooserCombo;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;

/**
 *
 * @author Belthazod
 */
public class AdjustmentController {
    ProductController productController;
    private TableManager adjustmentTableManager;
    private TableManager adjustmentListTableManager;
    private TableManager adjustmentHistoryTableManager;
    private DatabaseConnector dbConnector = DatabaseConnector.getInstance();
    private JTextArea remarksInput;
    private DateChooserCombo dateAdjusted;
    private JDialog summaryDialog;
    private TableManager summaryTableManager;
    private JTextArea finalRemarksInput;
    private JLabel productName;
    private JLabel supplier;
    private JLabel category;
    private JLabel quantity;
    private JComboBox operation;
    private JTextField count;
    private JDialog adjustDialog;
    private JTextArea remarks;    
    private DateChooserCombo dateTo;
    private DateChooserCombo dateFrom;
    private JComboBox<ComboItem> filterCategoryComboBox;
    private JComboBox<ComboItem> filterSupplierComboBox;
    private JLabel clearMark;
    private JTextField productSearchInput;
    
    public AdjustmentController(JTable adjustmentTable, JTable adjustmentList, 
            JLabel productName, JLabel supplier, JLabel category, JLabel quantity,
            JComboBox operation, JTextField count, DateChooserCombo dateAdjusted,
            JDialog adjustDialog, JTextArea remarks, DateChooserCombo dateTo, 
            DateChooserCombo dateFrom, JTable adjustmentHistoryTable, JComboBox<ComboItem> filterCategoryComboBox,
            JComboBox<ComboItem> filterSupplierComboBox, JLabel clearMark, JTextField productSearchInput){
        productController = new ProductController();
        adjustmentTableManager = new TableManager(adjustmentTable);
        adjustmentListTableManager = new TableManager(adjustmentList);
        adjustmentHistoryTableManager = new TableManager(adjustmentHistoryTable);
        this.filterCategoryComboBox = filterCategoryComboBox;
        this.filterSupplierComboBox = filterSupplierComboBox;
        this.clearMark = clearMark;
        this.productSearchInput = productSearchInput;
        this.finalRemarksInput = finalRemarksInput;
        this.productName = productName;
        this.supplier = supplier;
        this.category = category;
        this.quantity = quantity;
        this.operation = operation;
        this.count = count;
        this.dateAdjusted = dateAdjusted;
        this.adjustDialog = adjustDialog;
        this.remarks = remarks;
        this.dateTo = dateTo;
        this.dateFrom = dateFrom;
        
//        adjustmentListTableManager.hideColumn(4);
//        adjustmentListTableManager.hideColumn(5);
//        adjustmentListTableManager.hideColumn(6);
//        adjustmentListTableManager.hideColumn(7);
//        adjustmentListTableManager.hideColumn(8);
    }
    
    public void adjustEntries(){
        try{
            int currentQuantity = Integer.parseInt(adjustmentTableManager.getValueAt(adjustmentTableManager.getSelectedRow(), 4));
            String productName = adjustmentTableManager.getValueAt(adjustmentTableManager.getSelectedRow(), 1);
            String productID = adjustmentTableManager.getValueAt(adjustmentTableManager.getSelectedRow(), 0);
            String Supplier = adjustmentTableManager.getValueAt(adjustmentTableManager.getSelectedRow(), 2);
            String category = adjustmentTableManager.getValueAt(adjustmentTableManager.getSelectedRow(), 3);
            
            String reason = remarks.getText();
            String oprtn = operation.getSelectedItem().toString();
            String qtyAdjusted = count.getText();
            int adjustedQty = Integer.parseInt(qtyAdjusted);
            
            int adjustedQuantity = 0;
            String operatn = "";
            if(oprtn.equals("Add")){
                adjustedQuantity = currentQuantity + adjustedQty;   
                operatn = "addition";
            }else if(oprtn.equals("Subtract")){
                adjustedQuantity = currentQuantity - adjustedQty;
                operatn = "subtraction";
            }
            
            String quantity = Integer.toString(currentQuantity);
            String adjstedQty = Integer.toString(adjustedQuantity);
            String[] values = {productName, Supplier, quantity, adjstedQty, productID, category, qtyAdjusted, operatn, reason};
                        
            
        
            adjustmentListTableManager.addRowContent(values);
            adjustDialog.dispose();
            remarks.setText("");
            count.setText("");
        }catch(NumberFormatException nfe){
            JOptionPane.showMessageDialog(null, "Count cannot be empty.", "Invalid Input", JOptionPane.ERROR_MESSAGE);
        }catch(Exception e){
            e.printStackTrace();
        }
    }
    
    public void openSummaryDialog(){
        
    }
    
    public void confirmAdjustmentDialog(){
        
        String adjustmentDate = InputValidator.dateFormat(dateAdjusted);
        String reason = remarks.getText();
        String[] values = {adjustmentDate, reason};
        
        try{
            int result = JOptionPane.showConfirmDialog(null, "Confirm Adjustment?", "Confirm Adjustment", JOptionPane.YES_NO_OPTION);
                if(result == 0){
        dbConnector.insert("INSERT INTO adjustment (date_adjusted, reason) VALUES (?, ?)", values);
            ResultSet rs = dbConnector.query("SELECT adjustment_id FROM adjustment ORDER BY 1 DESC");
                rs.next();
                String adjustmentID = rs.getString(1);
                rs.close();
                for(int row = 0; row < adjustmentListTableManager.getRowCount(); row++){
                String productID = adjustmentListTableManager.getValueAt(row, 4);
                String operation = adjustmentListTableManager.getValueAt(row, 7);
                String qtyAdjusted = adjustmentListTableManager.getValueAt(row, 6);
                String adjustedQuantity = adjustmentListTableManager.getValueAt(row, 3);
                String[] values2 = {adjustmentID, productID, operation, qtyAdjusted};
                String[] values3 = {adjustedQuantity, productID}; 
            dbConnector.insert("INSERT INTO adjustment_details(adjustment_id, product_id, operation, quantity_adjusted) VALUES (?, ?, ?, ?)", values2);
            dbConnector.update("UPDATE product SET physical_count = ? WHERE Product_id = ?", values3);
                }
            adjustmentTableManager.clearTableContents();
            adjustmentListTableManager.clearTableContents();
            //JOptionPane.showMessageDialog(null, "Quantity adjusted.", "Adjustment", JOptionPane.INFORMATION_MESSAGE);
            ProductsUI.updateAdminProductsTable();
            JOptionPane.showMessageDialog(null, "Quantity adjusted.", "Adjustment", JOptionPane.INFORMATION_MESSAGE);
                }
        }catch(SQLException sqle){
            sqle.printStackTrace();
        }
    }
    
    public void adjustDialog(){
        boolean exist = false;
        String productID = adjustmentTableManager.getValueAt(adjustmentTableManager.getSelectedRow(), 0);
        for(int row = 0; row < adjustmentListTableManager.getRowCount(); row++){
                    String truckProductID = adjustmentListTableManager.getValueAt(row, 4);
                    exist = productID.equals(truckProductID);
                } 
        if(!exist){
        String Name = adjustmentTableManager.getValueAt(adjustmentTableManager.getSelectedRow(), 1);
        String Supplier = adjustmentTableManager.getValueAt(adjustmentTableManager.getSelectedRow(), 2);        
        String Category = adjustmentTableManager.getValueAt(adjustmentTableManager.getSelectedRow(), 3);
        String Quantity = adjustmentTableManager.getValueAt(adjustmentTableManager.getSelectedRow(), 4);
        
        productName.setText(Name);
        supplier.setText(Supplier);
        category.setText(Category);
        quantity.setText(Quantity);
        remarks.setText("");
        count.setText("");
        adjustDialog.setVisible(true);
        }else{
            JOptionPane.showMessageDialog(null, "Item already in the list.", "Invalid Input", JOptionPane.ERROR_MESSAGE);
        }
    }
    
    public void updateHistoryReport(){
        adjustmentHistoryTableManager.clearTableContents();
        DateFormat dfto = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sdf = new SimpleDateFormat("MMMMM d, yyyy");
        String toDate = InputValidator.dateFormat(dateFrom);
        String fromDate = InputValidator.dateFormat(dateTo);
        try{
            ResultSet rs = dbConnector.query("SELECT date_adjusted, Name, quantity_adjusted, reason, operation FROM adjustment JOIN adjustment_details using(adjustment_id) JOIN product using(Product_id) WHERE adjustment.adjustment_id = adjustment_details.adjustment_id AND adjustment_details.product_id = product.Product_id AND date_adjusted between '" + toDate + "' and '" + fromDate + "' ORDER BY 1 DESC");

            while(rs.next()){
                String date = rs.getString(1);
                java.util.Date dateFormat = dfto.parse(date);
                String dateReport = sdf.format(dateFormat);
                String name = rs.getString(2);
                String quantity = rs.getString(3);
                String description = rs.getString(4);
                String operation = rs.getString(5);
                
                String[] reportDetails = {dateReport, name, operation, quantity, description};
                adjustmentHistoryTableManager.addRowContent(reportDetails);
            }
        }catch(SQLException sqlE){
            sqlE.printStackTrace();
        }catch(Exception e){
            e.printStackTrace();
        }
                
    }
    
    public void filterProducts(){

         ArrayList<Product> productList = productController.getProducts();
        
         if(filterCategoryComboBox.getSelectedItem()!=null && productList != null && filterSupplierComboBox.getSelectedItem()!=null){
            adjustmentTableManager.clearTableContents();
            ArrayList<Product> filteredByCategoryList = filterByCategory( productList);
            ArrayList<Product> filteredByCategoryAndSupplierList = filterBySupplier(filteredByCategoryList);
            
            if(clearMark.isVisible()){
                searchProduct();
            }else{
                for(Product product:filteredByCategoryAndSupplierList){

                        String[] productValues = {product.getProductID(), product.getName(),
                            product.getSupplierName(),
                            product.getTypeName(),                     
                            product.getPhysicalCount()};

                        adjustmentTableManager.addRowContent(productValues);
                  
                }
            }
         }        
    }
    
         public ArrayList<Product> filterByCategory(ArrayList<Product> productList){
         ArrayList<Product> filteredProductList = new ArrayList<Product>();
         if(filterCategoryComboBox.getSelectedItem().toString().equals("All")){
             return productList;
         }else{
            for(Product product:productList){
                if(filterCategoryComboBox.getSelectedItem().toString().equals(product.getTypeName())){
                    filteredProductList.add(product);
                }
            }
            return filteredProductList;
         }
     }
         
         public ArrayList<Product> filterBySupplier(ArrayList<Product> productList){
         ArrayList<Product> filteredProductList = new ArrayList<Product>();
         if(filterSupplierComboBox.getSelectedItem().toString().equals("All")){
             return productList;
         }else{
            for(Product product:productList){
                if(filterSupplierComboBox.getSelectedItem().toString().equals(product.getSupplierName())){
                    filteredProductList.add(product);
                }
            }
            return filteredProductList;
         }
     }
    
        public void searchProduct(){
        String productName = productSearchInput.getText();
        
        ArrayList<Product> productList = productController.getProducts();
        adjustmentTableManager.clearTableContents();
        
        ArrayList<Product> filteredByCategoryList = filterByCategory(productList);
        ArrayList<Product> filteredBySupplierAndCategoryList = filterBySupplier(filteredByCategoryList);
        for(Product product: filteredBySupplierAndCategoryList){
            if(product.getName().toLowerCase().contains(productName.toLowerCase())){
                String[] adminCompleteValues = {product.getProductID(), product.getName(),
                    product.getSupplierName(),
                    product.getTypeName(),                     
                    product.getPhysicalCount()};
                adjustmentTableManager.addRowContent(adminCompleteValues);
            }
        }
        if(productName.equals("")){
            clearMark.setVisible(false);
        }else{
            clearMark.setVisible(true);
        }
    }
    
    public void clearSearch(){
        productSearchInput.setText("");
        searchProduct();
        clearMark.setVisible(false);
    }
    
    public void removeSelectedRow(){
        adjustmentListTableManager.deleteRow();
    }
    
    public void clearList(){
        int result = JOptionPane.showConfirmDialog(null, "Are you sure you want to clear the list?", "Confirm Checkout", JOptionPane.YES_NO_OPTION);
        if(result == 0){
        adjustmentListTableManager.clearTableContents();
    }
    }
    
     public void justDClickIt(JTable table){
    table.addMouseListener(new MouseAdapter() {
    public void mousePressed(MouseEvent me) {
        JTable table =(JTable) me.getSource();
        Point p = me.getPoint();
        int row = table.rowAtPoint(p);
        if (me.getClickCount() == 2) {
            adjustDialog();
        }
    }
        });
    }
}
